﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RCREEE.Library;
using RCREEE.Library.Entities;
using System.Data;

namespace RCREEE.Web
{
    public partial class EnergyConsumptionDevelopment : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                //// Add the language code to session
                //Session.Add("LanguageCode", 1033);

                // Get all master Energy Consumptions Development items
                EnergyConsumptionDevelopmentItemValue _energy = new EnergyConsumptionDevelopmentItemValue();
                int LanguageCode = Convert.ToInt32(Session["LanguageCode"]);
                DataTable dtEnergyConsumptionItems = _energy.GetAllMasterEnergyConsumptions(LanguageCode, 0);

                // Add contacts datatable to the current session
                Session.Add("dtEnergyConsumptionItems", dtEnergyConsumptionItems);

                // Bulid the items Tree
                BuildTree(tvMasterItems, 0);

                ddlCountries.DataBind();

                #region Table Permissions

                // Table declarations

                //DataTable dtPermissions = new DataTable();

                //dtPermissions.Columns.Add("CountryId", typeof(int));
                //dtPermissions.Columns.Add("CanEdit", typeof(bool));

                //// New Row .. assigning permissions
                //DataRow drPermission = dtPermissions.NewRow();
                //drPermission["CountryId"] = 1;
                //drPermission["CanEdit"] = true;

                //dtPermissions.Rows.Add(drPermission);

                //// Add table to the session object
                //Session.Add("dtPermissions", dtPermissions);

                #endregion


            }
            dvDetails.AutoGenerateEditButton = CanEdit(Convert.ToInt32(ddlCountries.SelectedValue));
        }

        /// <summary>
        /// Fill The tree nodes with Items From dtEnergyConsumptionDevelopment
        /// </summary>
        /// <param name="ItemsTree">Name of TreeView Control to be built</param>
        private void BuildTree(TreeView ItemsTree, int ExceptionItemId)
        {
            // Refresh data if table in session is null
            if (Session["dtEnergyConsumptionItems"] == null)
                RefreshEnergyConsumptionMasterTable(ExceptionItemId);

            ItemsTree.Nodes.Clear();

            // Get All Parent Items
            DataRow[] currentRows = ((DataTable)Session["dtEnergyConsumptionItems"]).Select("ParentItemId = 0");
            if (currentRows.Length > 0)
            {
                // Loop Through the parent Items
                foreach (DataRow dr in currentRows)
                {
                    // Create node
                    TreeNode parentNode = new TreeNode(dr["ItemName"].ToString(), dr["ItemId"].ToString());

                    // Get children nodes for the current node if exist
                    List<TreeNode> childNodes = GetChildren(Convert.ToInt32(dr["ItemId"]));

                    // if childrenNodes exists
                    if (childNodes != null)

                        // Add children nodes to the parent
                        foreach (TreeNode childNode in childNodes)
                            parentNode.ChildNodes.Add(childNode);

                    // Add the node to the tree
                    ItemsTree.Nodes.Add(parentNode);
                }
            }
        }

        /// <summary>
        /// Gets All Children related to a specifec Parent (Item Id)
        /// </summary>
        /// <param name="currentItemId">Id of the ParentItem to get its children</param>
        /// <returns>List of TreeNodes related to the current Parent Item, NULL if it has no children</returns>
        private List<TreeNode> GetChildren(int currentItemId)
        {
            // refresh data if table in session is null
            if (Session["dtEnergyConsumptionItems"] == null)
                RefreshEnergyConsumptionMasterTable(0);

            // Get all children nodes for the current parent
            DataRow[] currentRows = ((DataTable)Session["dtEnergyConsumptionItems"]).Select("ParentItemId = " + currentItemId);

            // if xhildren exist
            if (currentRows.Length > 0)
            {
                //create a temp List of tree nodes
                List<TreeNode> tempChildNodes = new List<TreeNode>();
                foreach (DataRow dr in currentRows)
                {
                    // create a Tree node to hold the current child
                    TreeNode node = new TreeNode(dr["ItemName"].ToString(), dr["ItemId"].ToString());

                    // get children nodes of the current Child Node 
                    List<TreeNode> childNodes = GetChildren(Convert.ToInt32(dr["ItemId"]));
                    // if children exist ... add them to the current child
                    if (childNodes != null)
                        foreach (TreeNode childNode in childNodes)
                            node.ChildNodes.Add(childNode);

                    // add the current child node to the temp list
                    tempChildNodes.Add(node);
                }
                // return the temp list
                return tempChildNodes;
            }
            else
                // return null .. as no children exist
                return null;
        }

        /// <summary>
        /// Refresh The Table EnergyConsumptionMaster with all Items from database, and reinsert it in the session object
        /// </summary>
        /// <param name="ExceptionItemId"> Item Id to be excluded form the table</param>
        private void RefreshEnergyConsumptionMasterTable(int ExceptionItemId)
        {
            int LanguageCode = Convert.ToInt32(Session["LanguageCode"]);
            DataTable dtEnergyConsumptionItems = new DataTable();
            EnergyConsumptionDevelopmentItemValue _energy = new EnergyConsumptionDevelopmentItemValue();

            // Get All Energy Items data for database
            dtEnergyConsumptionItems = _energy.GetAllMasterEnergyConsumptions(LanguageCode, ExceptionItemId);

            // Remove table form the session object
            Session.Remove("dtEnergyConsumptionItems");

            // Add Eneregy consumption datatable to the current session
            Session.Add("dtEnergyConsumptionItems", dtEnergyConsumptionItems);
        }

        /// <summary>
        /// Search all nodes exist in the given tree for a given value, if found Set node as SELECTED
        /// </summary>
        /// <param name="_tree">TreeView name to search in</param>
        /// <param name="searchValueparam"> Search Value (ParentItemId)</parm>
        private void SetTreeSelectedNode(TreeView _tree, string searchValue)
        {
            // Loop throughall tree nodes
            foreach (TreeNode node in _tree.Nodes)
            {
                // If Value of the current node equals the search value
                if (node.Value == searchValue)
                {
                    // Set the current node as selected
                    node.Select();
                    break;
                }
                else
                {
                    // If the current node has children
                    if (node.ChildNodes.Count > 0)
                        // Perform a recursive search through the children of the current node
                        SearchRecursive(node, searchValue);
                }
            }
        }

        /// <summary>
        /// Search the current tree node and its children for a specific Value, set as selected node if FOUND
        /// </summary>
        /// <param name="node">Tree Node name</param>
        /// <param name="searchValue">Search Value (ParentItemId)</param>
        private void SearchRecursive(TreeNode node, string searchValue)
        {
            // Loop through The children of the current node
            foreach (TreeNode childNode in node.ChildNodes)
            {
                // check if the current node value equals the search value
                if (childNode.Value == searchValue)
                {
                    // set the current node as selected
                    childNode.Select();
                    break;
                }
                else
                    // if the current node has children
                    if (childNode.ChildNodes.Count > 0)
                        // perform a recursive search through the children of the current child node
                        SearchRecursive(childNode, searchValue);
            }

        }

        private void BindDetailsView()
        {
            if (ddlCountries.SelectedItem != null && ddlCountries.SelectedItem.Value != "0" && tvMasterItems.SelectedNode != null)
            {
                EnergyConsumptionDevelopmentItemValue _energy = new EnergyConsumptionDevelopmentItemValue();
                DataTable dtSource = _energy.GetOneEneregyConsumptionValuesById(Convert.ToInt32(tvMasterItems.SelectedNode.Value),
                                                                    Convert.ToInt32(ddlCountries.SelectedItem.Value));

                dvDetails.DataSource = dtSource;
                dvDetails.DataBind();

            }
        }

        protected void tvMasterItems_SelectedNodeChanged(object sender, EventArgs e)
        {
            BindDetailsView();
            dvDetails.DataBind();
        }

        protected void ddlCountries_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindDetailsView();
        }

        protected void dvDetails_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
        {
            EnergyConsumptionDevelopmentItemValue _energy = new EnergyConsumptionDevelopmentItemValue();

            foreach (DetailsViewRow dvRow in dvDetails.Rows)
            {
                if (dvRow.Cells[0].Text != "")
                {
                    ItemValue tempItem = new ItemValue();
                    tempItem.Year = Convert.ToInt32(dvRow.Cells[0].Text);
                    tempItem.Value = ((TextBox)dvRow.Cells[1].Controls[0]).Text;
                    _energy.ItemValues.Add(tempItem);
                }
            }
            _energy.ItemId = Convert.ToInt32(tvMasterItems.SelectedNode.Value);
            _energy.CountryId = Convert.ToInt32(ddlCountries.SelectedValue);
            _energy.UpdateEnergyConsumptionItemValues();
            e.Cancel = true;
            dvDetails.ChangeMode(DetailsViewMode.ReadOnly);
            BindDetailsView();
        }

        protected void dvDetails_ModeChanging(object sender, DetailsViewModeEventArgs e)
        {
            //if (e.NewMode == DetailsViewMode.Edit)
            //{
            //    dvDetails.ChangeMode(DetailsViewMode.Edit);
            //    FillGridView();
            //}
            //if (e.CancelingEdit)
            //{
            //    dvDetails.ChangeMode(DetailsViewMode.ReadOnly);
            //    FillGridView();
            //}

            dvDetails.ChangeMode(e.NewMode);

            if (e.NewMode != DetailsViewMode.Insert)
            {
                BindDetailsView();
            }
            

        }

        protected void dvDetails_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e)
        {
            e.KeepInEditMode = false;
            dvDetails.ChangeMode(DetailsViewMode.ReadOnly);
        }

        public bool CanEdit(int CountryId)
        {
            //if (Session["dtPermissions"] == null)
            //{
            //    #region Table Permissions
            //    // Table declarations
            //    DataTable dtPermissions = new DataTable();

            //    dtPermissions.Columns.Add("CountryId", typeof(int));
            //    dtPermissions.Columns.Add("CanEdit", typeof(bool));

            //    // New Row .. assigning permissions
            //    DataRow drPermission = dtPermissions.NewRow();
            //    drPermission["CountryId"] = 1;
            //    drPermission["CanEdit"] = true;

            //    dtPermissions.Rows.Add(drPermission);

            //    Session.Remove("dtPermissions");

            //    // Add table to the session object
            //    Session.Add("dtPermissions", dtPermissions);
            //    #endregion
            //}

            try
            {
                DataRow[] dr = ((DataTable)Session["Permissions"]).Select("CountryId = " + CountryId.ToString());

                if (dr.Length > 0)
                {
                    return Convert.ToBoolean(dr[0]["CanUpdate"]);
                }
                else
                    return false;
            }
            catch (Exception exc)
            {
                return false;
            }
        }

    }
}